<template>
  <view
    class="section-item u-border-bottom"
    @click="onStartLearning(item)"
    :data-theme="globPrimary"
  >
    <view
      class="tag fs22 mr14 u-border"
      :class="{ active: position }"
      v-if="item.course_type == 1 && !$u.test.empty(item.section_data)"
    >
      {{ item.section_data.data_type_text }}
    </view>
    <view class="title u-line-1 mr14" :class="{ active: position }">{{ item.title }}</view>
    <!-- 未购买课时 -->
    <template v-if="item.is_buy == 0">
      <template v-if="!$u.test.empty(item.live_rate)">
        <view class="fs22 gray mlauto mr14">
          {{ getFormateDate(item.start_time) }}-{{ item.end_time | date('hh:MM') }}
        </view>
      </template>
      <view class="mr14" v-if="item.audition > 0">
        <u-tag bg-color="#67c23a" mode="dark" size="mini" text="可试看" />
      </view>
      <view class="mr14" v-if="item.price > 0">
        <u-tag
          color="#f54030"
          border-color="#f54030"
          mode="plain"
          size="mini"
          :text="item.price | formatCurrency"
        />
      </view>
    </template>
    <template v-else>
      <!-- 点播课程进度 -->
      <template v-if="!$u.test.empty(item.section_rate)">
        <!-- 播放中 -->
        <view class="playing mlauto mr14" v-if="position">
          <view class="playing__bar playing__bar1"></view>
          <view class="playing__bar playing__bar2"></view>
          <view class="playing__bar playing__bar3"></view>
          <view class="playing__bar playing__bar4"></view>
        </view>
        <block v-else>
          <!-- 未开始 -->
          <u-image
            width="72rpx"
            height="32rpx"
            v-if="courseBuy == 0 && item.section_rate.status == 957"
            src="@/static/images/yigouamai.png"
          ></u-image>
          <!-- 学习中 -->
          <u-icon
            class="mlauto mr14"
            custom-prefix="edu-icon"
            name="ziyuan"
            :color="globPrimaryColor"
            v-if="item.section_rate.status == 999"
          ></u-icon>
          <view class="fs22 gray" v-if="item.section_rate.status == 999">
            已学习{{ item.section_rate.current_time | formatSeconds('hh:mm:ss') }}
          </view>
          <!-- 已完成 -->
          <u-image
            class="mlauto mr14"
            width="28rpx"
            height="28rpx"
            v-if="item.section_rate.status == 992"
            src="@/pageCourse/static/images/comment_fin_icon.png"
          ></u-image>
          <view class="fs22 gray" v-if="item.section_rate.status == 992">
            {{ item.section_rate.status_text }}
          </view>
        </block>
      </template>
      <!-- 直播课程进度 -->
      <template v-if="!$u.test.empty(item.live_rate)">
        <!-- 未开始 -->
        <u-image
          width="72rpx"
          height="32rpx"
          v-if="courseBuy == 0 && item.live_rate.status == 957"
          src="@/static/images/yigouamai.png"
        ></u-image>
        <view class="fs22 gray mlauto mr14" v-if="item.live_rate.status == 957">
          {{ getFormateDate(item.start_time) }}-{{ item.end_time | date('hh:MM') }}
        </view>
        <!-- 直播中 -->
        <view class="playing mlauto mr14" v-if="item.live_rate.status == 999">
          <view class="playing__bar playing__bar1"></view>
          <view class="playing__bar playing__bar2"></view>
          <view class="playing__bar playing__bar3"></view>
          <view class="playing__bar playing__bar4"></view>
        </view>
        <view class="fs22 text-primary" v-if="item.live_rate.status == 999">
          {{ item.live_rate.status_text }}
        </view>
        <!-- 已结束 -->
        <view class="fs22 gray mlauto" v-if="item.live_rate.status == 992">
          <template
            v-if="
              !$u.test.empty(item.live_rate.cc_replay_id) ||
              !$u.test.empty(item.live_rate.cc_replay_url)
            "
          >
            观看回放
          </template>
          <template v-else>无回放</template>
        </view>
      </template>
    </template>
    <!-- 解锁 -->
    <u-icon
      class="mlauto"
      name="lock-fill"
      color="#DCDFE6"
      size="34"
      v-if="
        item.course_type == 1 &&
        item.course_lock == 1 &&
        item.lock == 1 &&
        !getSectionPlayLock.includes(item.id)
      "
    ></u-icon>
    <!-- 人脸 -->
    <edu-face ref="refDirectoryFaceVerify" @confirm="onFaceVerifyConfirm"></edu-face>
  </view>
</template>

<script>
import { uploadFile } from '@/utils/uploadFile.js'
import { mapGetters, mapState } from 'vuex'
// #ifdef APP-PLUS
const ccLiveUniPlugin = uni.requireNativePlugin('Bokecc-CcLiveUniPlugin')
const ccSsktUniPlugin = uni.requireNativePlugin('Bokecc-CcClassUniPlugin')
// #endif
export default {
  props: {
    item: {
      type: Object,
      default: () => ({}),
    },
    // 定位
    position: {
      type: Boolean,
      default: false,
    },
    // 跳转到播放页时需要，点播和班级id不一样
    queryId: {
      type: Number,
      default: 0,
    },
    // 班级课
    classId: {
      type: Number,
      default: 0,
    },
    // 课程购买状态
    courseBuy: {
      type: Number,
      default: 0,
    },
    detailsInfo: {
      type: Object,
      default() {
        return {}
      },
    },
  },
  data() {
    return {
      directoryItemData: null,
    }
  },
  computed: {
    ...mapGetters({
      globPrimary: 'designSetting/getGlobTheme',
      globPrimaryColor: 'designSetting/getGlobThemeColor',
      courseCurrentPlayPosition: 'course/getCurrentPlayPosition',
      userInfo: 'user/getUserInfo',
      token: 'user/getToken',
    }),
    ...mapState({
      getCurrentPlayItem: (state) => state.course.currentPlayItem,
      getSectionPlayLock: (state) => state.course.currentSectionPlayLock,
    }),
  },
  options: { styleIsolation: 'shared' },
  methods: {
    // 开始学习
    onStartLearning(item) {
      // 已购买
      if (item.is_buy) {
        // 点播
        if (!this.$u.test.empty(item.section_rate)) {
          this.onJumpVideo(item)
        }
        // 直播
        if (!this.$u.test.empty(item.live_rate)) {
          this.onJumpLive(item)
        }
      } else {
        // 缓存课时的item
        this.$store.commit('course/setCurrentPlayItem', item)
        // 可试看
        if (item.audition > 0) {
          // 试看需要登录
          if (this.detailsInfo.look_need_login == 1) {
            this.$edu.judgeLogin(() => {
              this.onJump(item)
            })
          } else {
            this.onJump(item)
          }
        } else if (item.price > 0) {
          this.$edu.judgeLogin(() => {
            this.$u.route('/pageCourse/cart/section', {
              id: item.id,
            })
          })
        } else {
          this.$u.toast('课程未购买，请前往购买')
        }
      }
    },
    // 进入点播播放
    async onJumpVideo(item) {
      // 防止重复点击
      if (!this.position) {
        // 点播解锁模式
        if (item.course_type == 1 && item.course_lock == 1 && item.lock == 1) {
          let lock = await this.$edu.api
            .getCourseUnlock({
              course_id: item.course_id,
              section_id: item.id,
              class_id: this.classId,
            })
            .then((res) => {
              return res.data
            })
          if (!lock) {
            this.$u.toast('课时未解锁')
            return
          }
        }
        // 是否需要人脸识别
        if (this.detailsInfo.onhook_type == 3) {
          this.directoryItemData = item
          // #ifdef APP-PLUS
          this.$u.route('pages/face', {
            type: 1,
            scene_id: item.id,
            scene_type: 1,
            scene_key: 'course_section',
          })
          // #endif
          // #ifndef APP-PLUS
          this.$refs.refDirectoryFaceVerify.onFaceMessage()
          // #endif
          // 当前路由是详情页就跳转
          let pages = getCurrentPages()
          let page = pages[pages.length - 1]
          if (page.route == 'pageCourse/course/video/index') {
            uni.$emit('sectionPlayerPause')
          }
        } else {
          // 缓存课时的item
          this.$store.commit('course/setCurrentPlayItem', item)
          this.onJump(item)
        }
      }
    },
    onJump(item) {
      // 当前路由是详情页就跳转
      let pages = getCurrentPages()
      let page = pages[pages.length - 1]
      if (page.route == 'pageCourse/course/details') {
        this.$u.route('/pageCourse/course/video/index', {
          id: this.queryId,
          sid: item.id,
        })
      } else {
        uni.$emit('sectionPlayerPause')
        uni.$emit('sectionPlayerUpdate')
      }
    },
    // 进入直播播放
    onJumpLive(item) {
      let viewertoken = item.section_live.authtype == 0 ? `${this.token.ak}:${this.token.sk}` : ''
      // 缓存课时的item
      this.$store.commit('course/setCurrentPlayItem', item)
      // 未开始
      if (item.live_rate.status == 957) {
        this.$u.toast('直播未开始')
      }
      // 直播中
      else if (item.live_rate.status == 999) {
        /* #ifdef H5 */
        // 声网直播
        if (item.live_provider == 2) {
          this.$u.route('/pageCourse/live/index', {
            id: item.id,
          })
        }
        /* #endif */

        /* #ifdef H5 */
        // cc直播
        if (item.live_provider == 3) {
          if (item.section_live.live_type === 2) {
            // 云直播大班课
            this.$u.route('/pageCourse/cc_live/cc_live', {
              cc_room_id: item.section_live.cc_room_id,
              cc_userid: item.section_live.cc_userid,
              viewername: this.userInfo.nick_name,
              viewertoken: viewertoken,
            })
          } else if (item.section_live.live_type === 3) {
            // 云课堂小班课
            this.$u.route('/pageCourse/cc_live/cc_small_class', {
              viewertoken: viewertoken,
              roomid: item.section_live.cc_room_id,
              userid: item.section_live.cc_userid,
            })
          }
        }
        /* #endif */

        // #ifdef APP-PLUS
        // cc直播
        if (item.live_provider == 3) {
          if (item.section_live.live_type === 2) {
            // 云直播大班课
            uni.showLoading({
              title: '登录中，请稍后',
            })
            setTimeout(() => {
              uni.hideLoading()
            }, 3000)
            ccLiveUniPlugin.loginLive(
              {
                roomId: item.section_live.cc_room_id,
                accountId: item.section_live.cc_userid,
                userName: this.userInfo.nick_name,
                password: viewertoken,
              },
              (ret) => {
                let data = JSON.parse(ret)
                this.$u.toast(data.msg)
              }
            )
          } else if (item.section_live.live_type === 3) {
            // 云课堂小班课
            // role	登录角色，取值说明："0"为讲师，"1"为学员，"2"为旁听，"3"为隐身者，"4"为助教
            uni.showLoading({
              title: '登录中，请稍后',
            })
            setTimeout(() => {
              uni.hideLoading()
            }, 3000)
            ccSsktUniPlugin.loginByAccount(
              {
                roomId: item.section_live.cc_room_id,
                accountId: item.section_live.cc_userid,
                role: 1,
                userName: this.userInfo.nick_name,
                password: viewertoken,
              },
              (ret) => {
                let data = JSON.parse(ret)
                this.$u.toast(data.msg)
              }
            )
          }
        }
        // #endif
      }
      // 已结束/处理回放
      else if (item.live_rate.status == 992) {
        /* #ifdef H5 */
        // cc直播
        if (item.live_provider == 3) {
          if (item.section_live.live_type === 2) {
            // 大班课
            if (this.$u.test.empty(item.live_rate.cc_replay_id)) {
              this.$u.toast('无回放')
            } else {
              this.$u.route('/pageCourse/cc_live/cc_playback', {
                userId: item.section_live.cc_userid,
                roomId: item.section_live.cc_room_id,
                recordId: item.section_live.cc_replay_id,
                viewername: this.userInfo.nick_name,
                viewertoken: viewertoken,
              })
            }
          } else if (item.section_live.live_type == 3) {
            // 小班课
            if (this.$u.test.empty(item.live_rate.cc_replay_url)) {
              this.$u.toast('无回放')
            } else {
              console.log('cc_replay_url')
              this.$u.route('/pageCourse/cc_live/cc_small_class', {
                url: btoa(item.live_rate.cc_replay_url),
                viewertoken: viewertoken,
              })
            }
          }
        }
        /* #endif */

        // #ifdef APP-PLUS
        if (item.live_provider == 3) {
          if (item.section_live.live_type === 2) {
            if (this.$u.test.empty(item.live_rate.cc_replay_id)) {
              this.$u.toast('无回放')
            } else {
              uni.showLoading({
                title: '登录中，请稍后',
              })
              setTimeout(() => {
                uni.hideLoading()
              }, 3000)
              ccLiveUniPlugin.loginReplay(
                {
                  roomId: item.section_live.cc_room_id,
                  accountId: item.section_live.cc_userid,
                  recordId: item.section_live.cc_replay_id,
                  userName: this.userInfo.nick_name,
                  password: viewertoken,
                },
                (ret) => {
                  let data = JSON.parse(ret)
                  this.$u.toast(data.msg)
                }
              )
            }
          } else if (item.section_live.live_type == 3) {
            // cc直播小班课云课堂
            if (this.$u.test.empty(item.live_rate.cc_replay_url)) {
              this.$u.toast('无回放')
            } else {
              this.$u.route('/pageCourse/cc_live/cc_small_class', {
                url: btoa(item.live_rate.cc_replay_url),
                viewertoken: viewertoken,
              })
            }
          }
        }
        // #endif
      }
    },
    // 人脸验证
    onFaceVerifyConfirm(file) {
      uploadFile('/user/tencent/face/person/verify', file, {
        scene_key: 'course_section',
        scene_id: this.directoryItemData.id,
        scene_type: 1,
      })
        .then((res) => {
          // 缓存课时的item
          this.$store.commit('course/setCurrentPlayItem', this.directoryItemData)
          this.$u.toast(res.msg)
          this.onJump(this.directoryItemData)
          this.$refs.refDirectoryFaceVerify.onClose()
        })
        .catch((err) => {
          this.$u.toast(err.msg)
          this.$refs.refDirectoryFaceVerify.resetPhoto()
        })
    },
    getFormateDate(timestamp) {
      let now = new Date() // 当前
      if (timestamp.toString().length == 10) timestamp *= 1000
      let date = new Date(timestamp)
      const nextDate = function (date, amount = 1) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount)
      }
      // 当前年
      if (now.getFullYear() == date.getFullYear()) {
        if (this.$u.date(now) == this.$u.date(date)) {
          return this.$u.date(timestamp, '今天hh:MM')
        } else if (this.$u.date(nextDate(now)) == this.$u.date(date)) {
          return this.$u.date(timestamp, '明天hh:MM')
        } else {
          return this.$u.date(timestamp, 'mm月dd日 hh:MM')
        }
      } else {
        return this.$u.date(timestamp, 'yyyy年mm月dd日 hh:MM')
      }
    },
  },
  beforeDestroy() {
    uni.hideLoading()
  },
}
</script>

<style lang="scss" scoped>
.section-item {
  display: flex;
  align-items: center;
  margin-left: 30rpx;
  padding-right: 30rpx;
  height: 86rpx;
  position: relative;
  .tag {
    padding: 4rpx 7rpx;
    color: #6e6e6e;
    background: #f1f1f1;
    border-radius: 6rpx;
    white-space: nowrap;
    &.active {
      color: #ffffff;
      @include bg-color();
      &:after {
        @include border-color();
      }
    }
  }
  ::v-deep .u-tag {
    white-space: nowrap;
  }
  .label {
    /deep/.u-tag {
      border-radius: 18rpx 0 18rpx 0;
    }
  }
  .mr14 {
    margin-right: 14rpx;
  }
  .mlauto {
    margin-left: auto;
  }
  .title {
    font-size: 28rpx;
    font-weight: 400;
    color: $edu-content-color;
    &.active {
      @include text-color();
    }
  }
  .fs22 {
    font-size: 22rpx;
    white-space: nowrap;
  }
  .gray {
    color: #909399;
  }
  .text-primary {
    @include text-color();
  }
  .playing {
    flex: 0 0 32rpx;
    width: 32rpx;
    height: 34rpx;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    margin-left: auto;
    .playing__bar {
      width: 4rpx;
      height: 100%;
      border-radius: 3rpx;
      @include bg-color();
      animation: up-and-down 1.3s ease infinite alternate;
    }
    .playing__bar1 {
      height: 60%;
    }
    .playing__bar2 {
      height: 30%;
      animation-delay: -2.4s;
    }
    .playing__bar3 {
      height: 75%;
      animation-delay: -3.7s;
    }
    .playing__bar4 {
      height: 45%;
      animation-delay: -4.8s;
    }
    .play_text {
      font-size: 22rpx;
      @include text_color();
    }
  }
}

@keyframes up-and-down {
  10% {
    height: 30%;
  }
  30% {
    height: 100%;
  }
  60% {
    height: 50%;
  }
  80% {
    height: 75%;
  }
  100% {
    height: 20%;
  }
}
</style>
